from odoo import fields, models, api
from odoo.exceptions import UserError


class RPVolumeWeight(models.Model):
    _name = 'rp.volume.weight'
    _description = '体积重'
    _sql_constraints = [('unique_name', 'UNIQUE(name)', '名称必须唯一')]

    def _default_get_cm3kg(self):
        cm3kg = self.env['uom.uom'].search([('name', '=', 'cm³/kg')])
        return cm3kg.id if cm3kg else False

    name = fields.Char(string='名称', default='- -', compute='_depends_fulfill_name', store=True, )

    volume_weight = fields.Float(string='体积重', digits=(8, 1), default=0, help="用于计算当前体积的【应重】")
    volume_weight_uom_id = fields.Many2one(string='体积重单位', comodel_name='uom.uom', default=_default_get_cm3kg, domain=[('category_id', '=', 6)])

    @api.depends('volume_weight', 'volume_weight_uom_id')
    def _depends_fulfill_name(self):
        for s in self:
            number = s.volume_weight if s.volume_weight else '-'
            uom = s.volume_weight_uom_id.name if s.volume_weight_uom_id else '-'
            s.write({'name': '{} {}'.format(number, uom)})

    @api.constrains('volume_weight')
    def _check_info(self):
        for s in self:
            if s.volume_weight <= 0:
                raise UserError('体积重不能小于等于零')
